﻿using CPPEI.Coolzon.ServiceProxy.DataServiceRef;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CPPEI.Coolzon.Designer.Views
{
    /// <summary>
    /// StaticDataSourceWindow.xaml 的交互逻辑
    /// </summary>
    public partial class StaticDataSourceWindow : Window
    {
        private ObservableCollection<DataSourcePreviewModel> _staticDataSource = new ObservableCollection<DataSourcePreviewModel>();
        private string _staticDataSourceName;
        private bool _isNew = true;
        private Guid _staticDataSourceId = default(Guid);
        public StaticDataSourceWindow()
        {
            InitializeComponent();
            _dataGrid.ItemsSource = _staticDataSource;
            Event.NCL.NCLEventBus.Register(this);
        }
        public StaticDataSourceWindow(string staticDataSourceFilePath, Guid staticDataSourceId)
        {
            InitializeComponent();
            if (!string.IsNullOrWhiteSpace(staticDataSourceFilePath))
            {
                _isNew = false;
                _staticDataSourceId = staticDataSourceId;
                InitDataSource(staticDataSourceFilePath);
            }
            _dataGrid.ItemsSource = _staticDataSource;
            Event.NCL.NCLEventBus.Register(this);
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Event.NCL.NCLEventBus.Unregister(this);
        }

        private void InitDataSource(string staticDataSourceFilePath)
        {
            DataResult dataResult = CPPEI.Coolzon.UI.DataTask.StaticDataSourceManager.LoadDataFromFile(staticDataSourceFilePath);
            if (dataResult != null)
            {
                _name.Text = dataResult.Name;
                foreach (var series in dataResult.DataSeries)
                {
                    foreach (var item in series.DataItems)
                    {
                        DataSourcePreviewModel model = new DataSourcePreviewModel();
                        model.SeriesID = series.Id;
                        model.SeriesName = series.Name;
                        model.ItemID = item.Id;
                        model.ItemName = item.Name;
                        model.Value = item.Value;
                        _staticDataSource.Add(model);
                    }
                }
            }
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            _staticDataSource.Add(new DataSourcePreviewModel());
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (_dataGrid.SelectedItem != null)
            {
                _staticDataSource.Remove(_dataGrid.SelectedItem as DataSourcePreviewModel);
            }
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(_name.Text))
            {
                Coolzon.UI.CustomMessageBox.ShowWarning("名称不能为空", "提示");
                return;
            }
            System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z0-9\u4e00-\u9fa5]+$");
            if (!reg1.IsMatch(_name.Text))
            {
                Coolzon.UI.CustomMessageBox.ShowWarning("名称只能为汉字、字母或数字", "提示");
                return;
            }

            _staticDataSourceName = _name.Text;
            if (UIContext.Current.CurrentSolution.ExistStaticDataSource(_staticDataSourceName, _staticDataSourceId))
            {
                Coolzon.UI.CustomMessageBox.ShowWarning("名称已经存在", "提示");
                return;
            }

            if (_isNew)
            {
                Event.NCL.NCLEventBus.Publish(new Event.NCL.BeginGetLatestVersionEvent(UIContext.Current.CurrentSolution.ID, UIContext.Current.CurrentSolution.ID, UIContext.Current.Token));
            }
            else
            {
                SolutionTreeViewNode node = SolutionTreeViewNodeHelper.GetStaticDataSourceNode(_staticDataSourceId);
                List<SolutionTreeViewNode> nodeList = new List<SolutionTreeViewNode>();
                nodeList.Add(node);
                CheckOutThread.Start(nodeList, ReportProgress, Completed);
                ProgressbarWindow.Instance.ShowProgress(false);
            }
        }

        private void BeginCreateStaticDataSource()
        {
            if (UIContext.Current.SolutionNode != null && UIContext.Current.SolutionNode.NodeStatus == NodeStatus.CheckOut)
            {
                CreateStaticDataSource();
            }
            else
            {
                List<SolutionTreeViewNode> nodeList = new List<SolutionTreeViewNode>();
                nodeList.Add(UIContext.Current.SolutionNode);
                CheckOutThread.Start(nodeList, ReportProgress, Completed);
                ProgressbarWindow.Instance.ShowProgress(false);
            }
        }
        public void ReportProgress(Guid id, string name, int current, int total)
        {
            Dispatcher.Invoke(() =>
            {
                ProgressbarWindow.Instance.ReportProgress(current, total);
            });
        }

        public void Completed(bool HasError, int successed, int total)
        {
            ProgressbarWindow.Instance.Complete();
            if (HasError)
            {
                this.Dispatcher.Invoke(() =>
                {
                    Coolzon.UI.CustomMessageBox.ShowError("签出失败");
                });
                return;
            }
            if (_isNew)
            {
                CreateStaticDataSource();
            }
            else
            {
                UpdateStaticDataSource();
            }
        }

        private void UpdateStaticDataSource()
        {
            DataResult dataResult = new DataResult();
            dataResult.Name = _staticDataSourceName;
            List<DataSeries> dataSeriesList = new List<DataSeries>();
            if (_staticDataSource != null && _staticDataSource.Count > 0)
            {
                foreach (var item in _staticDataSource)
                {
                    DataSeries ds = dataSeriesList.Find(dataSeries => dataSeries.Id.Equals(item.SeriesID));
                    if (ds != null)
                    {
                        List<DataItem> dataItemList = ds.DataItems == null ? new List<DataItem>() : ds.DataItems.ToList();
                        DataItem di = new DataItem();
                        di.Id = item.ItemID;
                        di.Name = item.ItemName;
                        di.Value = item.Value;
                        dataItemList.Add(di);

                        ds.DataItems = dataItemList.ToArray();
                    }
                    else
                    {
                        ds = new DataSeries();
                        ds.Id = item.SeriesID;
                        ds.Name = item.SeriesName;

                        List<DataItem> dataItemList = ds.DataItems == null ? new List<DataItem>() : ds.DataItems.ToList();
                        DataItem di = new DataItem();
                        di.Id = item.ItemID;
                        di.Name = item.ItemName;
                        di.Value = item.Value;
                        dataItemList.Add(di);

                        ds.DataItems = dataItemList.ToArray();

                        dataSeriesList.Add(ds);
                    }
                }
            }
            dataResult.DataSeries = dataSeriesList.ToArray();
            Event.UI.UIEventBus.Publish(new Event.UI.UIUpdateStaticDataSourceEvent(dataResult.Name, CPPEI.Coolzon.UI.DataTask.StaticDataSourceManager.SaveDataToString(dataResult), _staticDataSourceId));

            this.Dispatcher.Invoke(() =>
            {
                this.DialogResult = true;
            });
        }

        private void CreateStaticDataSource()
        {
            DataResult dataResult = GetDataResult();
            Event.UI.UIEventBus.Publish(new Event.UI.UICreateStaticDataSourceEvent(dataResult.Name, CPPEI.Coolzon.UI.DataTask.StaticDataSourceManager.SaveDataToString(dataResult)));

            this.Dispatcher.Invoke(() =>
            {
                this.DialogResult = true;
            });
        }

        private DataResult GetDataResult()
        {
            DataResult dataResult = new DataResult();
            dataResult.Name = _staticDataSourceName;
            List<DataSeries> dataSeriesList = new List<DataSeries>();
            if (_staticDataSource != null && _staticDataSource.Count > 0)
            {
                foreach (var item in _staticDataSource)
                {
                    DataSeries ds = dataSeriesList.Find(dataSeries => dataSeries.Id.Equals(item.SeriesID));
                    if (ds != null)
                    {
                        List<DataItem> dataItemList = ds.DataItems == null ? new List<DataItem>() : ds.DataItems.ToList();
                        DataItem di = new DataItem();
                        di.Id = item.ItemID;
                        di.Name = item.ItemName;
                        di.Value = item.Value;
                        dataItemList.Add(di);

                        ds.DataItems = dataItemList.ToArray();
                    }
                    else
                    {
                        ds = new DataSeries();
                        ds.Id = item.SeriesID;
                        ds.Name = item.SeriesName;

                        List<DataItem> dataItemList = ds.DataItems == null ? new List<DataItem>() : ds.DataItems.ToList();
                        DataItem di = new DataItem();
                        di.Id = item.ItemID;
                        di.Name = item.ItemName;
                        di.Value = item.Value;
                        dataItemList.Add(di);

                        ds.DataItems = dataItemList.ToArray();

                        dataSeriesList.Add(ds);
                    }
                }
            }
            dataResult.DataSeries = dataSeriesList.ToArray();
            return dataResult;
        }

        [Common.Subscribe]
        public void OnEndGetSolutionListEvent(Event.NCL.EndGetLatestVersiontEvent @event)
        {
            if (@event.State == Event.NCL.NCLEventState.Finished)
            {
                ServiceProxy.DesignServiceRef.GetLatestVersionResponse response = @event.LatestVersion;
                this.Dispatcher.Invoke(() =>
                {
                    Designtime.Metadata.VSFile vsFile = Designtime.Metadata.VSFileMgr.GetFile(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution.ID, UIContext.Current.CurrentSolution.ID);
                    if (vsFile == null || response.ItemVersion > vsFile.Version)
                    {
                        Coolzon.UI.CustomMessageBox.ShowError("服务器存在新版本，请获取！");
                    }
                    else
                    {
                        BeginCreateStaticDataSource();
                    }
                });
            }
            else if (@event.State == Event.NCL.NCLEventState.Failure)
            {
                Coolzon.UI.CustomMessageBox.ShowError("场景创建失败！");
            }
        }
    }
}
